import React, { useState, useEffect } from 'react';
import { Card, Button, Modal, Select, Form, Table, Input, notification } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import '../../../style/Listofroles.scss';
import { auth_search } from '../../../utils/api';
import { connect } from "react-redux"
import { create_roleaddaction, create_roleeditaction, create_rolenewaddaction, create_roledeleteaction, create_rolesearchaction } from "../../../store/actionCreator/index"
import { useAuthregister } from "../../../hooks/Authoritymanage"

const { Search } = Input;
const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 6,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};
function Listofroles(props) {
    var [pagination, setPagination] = useState([{ current: 1, total: 10, pageSize: 10 }])
    var [roleid, setRoleid] = useAuthregister();
    const [form] = Form.useForm();
    const columns = [
        {
            title: '账号',
            dataIndex: 'user',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '电话',
            dataIndex: 'phone',
        },
        {
            title: '角色',
            dataIndex: ['role', "name"],
        },
        {
            title: '操作',
            render: (_, record) => (
                <div className="icon">
                    <i className='iconfont icon-bianji' onClick={() => { edit(record) }}>编辑</i>
                    <i className='iconfont icon-shanchu' onClick={() => { del(record) }}>删除</i>
                </div>
            ),
        },
    ];
    var [currentpage, setCurrentpage] = useState(1)
    var handleChange = (pagination) => {
        console.log(pagination);
        setPagination(pagination)
        setCurrentpage(pagination.current);
    }
    var del = (record) => {
        console.log(record);
        handleChange(pagination)
        props.del({ key: record.key, searchKey: '', page: currentpage, count: 50 })
    }


    useEffect(() => {
        props.add();
    }, [])
    var onSearch = (value) => {
        console.log(value)
        if (value) {
            props.search(value);
            // auth_search({ searchKey: value, page: 1, count: 50 }).then((res) => {
            //     console.log(pagination.current);

            //     console.log(res.data);
            //     if (res.data.code == 200 && res.data.list.length != 0) {
            //         notification.success({
            //             message: res.data.msg,
            //             duration: 1
            //         })
            //         setData(res.data.list);
            //         setPagination(pagination);
            //     } else {
            //         notification.error({
            //             message: "未查询到匹配的数据",
            //             duration: 1
            //         })
            //         setData(res.data.list);

            //     }

            // })
        } else {
            notification.warning({ message: "请至少输入一个字符", duration: 1 });
        }
    }
    // 弹框的初始状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        form.submit();
        setTimeout(() => {
            setIsModalOpen(false);
        }, 800);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    var adddata = () => {
        showModal();
    }
    const onFinish = (values) => {
        console.log(values);
        props.newadd({ user: values.user, name: values.name, phone: values.phone, email: values.email, role: values.role, page: currentpage });
        setTimeout(() => {
            setPagination(pagination)
        }, 500);
    };



    // 编辑  
    var [status, setStatus] = useState(false)
    var changeForm = () => {
        setStatus(true);
    }
    const [isModalOpen1, setIsModalOpen1] = useState(false);
    const showModal1 = () => {
        setIsModalOpen1(true);
    };
    const handleOk1 = () => {
        form.submit();
    };
    const handleCancel1 = () => {
        setIsModalOpen1(false);
    };
    const onFinish1 = (values) => {
        if (status) {//已作出修改 在编辑
            console.log(values);
            props.edit({ key: studentid, ...values });
            setTimeout(() => {
                setIsModalOpen1(false);
            }, 800);
        } else {
            notification.error({
                message: "没有进行任何操作",
            })
        }
    };
    var [studentid, setStudentid] = useState(null)
    var edit = (record) => {
        console.log(record);
        setStudentid(record.key)
        form.setFieldsValue(record);
        form.setFieldsValue({ role: record.role._id })
        showModal1();
    }
    return (
        <div className='listofroles'>
            <Card bordered={false} >
                <h4 style={{ fontSize: 22 }}> 角色列表</h4>
                <div className="list">
                    <Search style={{ width: 400, padding: "10px 20px 10px 0" }} placeholder="请输入搜索的员工姓名" onSearch={onSearch} enterButton />
                    <Button type="primary" onClick={() => { adddata() }}>新增</Button>
                    <>
                        <Modal title="添加用户" okText="确定" cancelText="取消" centered open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                            <Form
                                {...formItemLayout}
                                form={form}
                                name="Register"
                                onFinish={onFinish}

                                scrollToFirstError
                            >
                                <Form.Item
                                    name="user"
                                    label="账号"
                                    rules={[
                                        {
                                            type: 'text',
                                            message: 'The input is not valid user!',
                                        },

                                        {
                                            required: true,
                                            message: 'Please input your user!',
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="name"
                                    label="姓名"
                                    tooltip="What do you want others to call you?"
                                    rules={[
                                        {
                                            required: true,
                                            message: 'Please input your name!',

                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(?:[\u4e00-\u9fa5·]{2,16})$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('姓名至少2位且是中文');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="phone"
                                    label="手机号"
                                    rules={[
                                        {
                                            // type: 'number',
                                            required: true,
                                            message: 'Please input your phone number!',
                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('手机号不合规范');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>


                                <Form.Item
                                    name="email"
                                    label="邮箱"
                                    rules={[
                                        {
                                            // type: 'number',
                                            required: true,
                                            message: 'Please input your phone number!',
                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('请输入正确的邮箱格式');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>



                                <Form.Item
                                    name="role"
                                    label="角色"
                                    rules={[
                                        {
                                            required: true,
                                            message: 'Please select role!',
                                        },
                                    ]}
                                >
                                    <Select placeholder="选择角色">
                                        {
                                            roleid.map((item, index) => {
                                                return (

                                                    <Option key={index} value={item._id}>{item.name}</Option>

                                                )
                                            })
                                        }
                                    </Select>
                                </Form.Item>

                            </Form>
                        </Modal>
                    </>

                    <>
                        <Modal title="编辑用户" okText="确定" cancelText="取消" centered open={isModalOpen1} onOk={handleOk1} onCancel={handleCancel1}>
                            <Form
                                {...formItemLayout}
                                form={form}
                                name="Register"
                                onFinish={onFinish1}
                                onChange={changeForm}
                                scrollToFirstError
                            >
                                <Form.Item
                                    name="user"
                                    label="账号"
                                    rules={[
                                        {
                                            type: 'text',
                                            message: 'The input is not valid user!',
                                        },

                                        {
                                            required: true,
                                            message: 'Please input your user!',
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="name"
                                    label="姓名"
                                    tooltip="What do you want others to call you?"
                                    rules={[
                                        {
                                            required: true,
                                            message: 'Please input your name!',

                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(?:[\u4e00-\u9fa5·]{2,16})$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('姓名至少2位且是中文');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="phone"
                                    label="手机号"
                                    rules={[
                                        {
                                            // type: 'number',
                                            required: true,
                                            message: 'Please input your phone number!',
                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('手机号不合规范');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>


                                <Form.Item
                                    name="email"
                                    label="邮箱"
                                    rules={[
                                        {
                                            // type: 'number',
                                            required: true,
                                            message: 'Please input your phone number!',
                                        },
                                        {
                                            validator: (rule, value) => {
                                                let reg = new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
                                                if (reg.test(value) == false) {
                                                    return Promise.reject('请输入正确的邮箱格式');
                                                } else {
                                                    return Promise.resolve();
                                                }
                                            }
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>



                                <Form.Item
                                    name="role"
                                    label="角色"
                                    rules={[
                                        {
                                            required: true,
                                            message: 'Please select role!',
                                        },
                                    ]}
                                >
                                    <Select placeholder="选择角色">
                                        {
                                            roleid.map((item, index) => {
                                                return (

                                                    <Option key={index} value={item._id}>{item.name}</Option>

                                                )
                                            })
                                        }
                                    </Select>
                                </Form.Item>

                            </Form>
                        </Modal>
                    </>
                </div>

                <Table size='middle' pagination={pagination} onChange={handleChange} columns={columns} dataSource={props.authlist} />
            </Card>

        </div>
    );
}

export default connect(
    (state) => {
        return {
            authlist: state.rolelist
        }
    },
    (dispatch) => {
        return {
            add: function () {
                dispatch(create_roleaddaction())
            },
            search: function (value) {
                dispatch(create_rolesearchaction(value))
            },
            del: function (item) {
                dispatch(create_roledeleteaction(item));
            },
            newadd: function (value) {
                dispatch(create_rolenewaddaction(value))
            },
            edit: function (record) {
                dispatch(create_roleeditaction(record))
            }

        }
    }
)(Listofroles);